package com.yunao.web.controller;

import com.yunao.commons.enums.ResultEnum;
import com.yunao.commons.serachcore.core.bean.Articles;
import com.yunao.commons.utils.ResultVOUtil;
import com.yunao.commons.vo.ResultVO;
import com.yunao.entity.User;
import com.yunao.service.IsearchService;
import com.yunao.web.annotation.UserLoginToken;
import com.yunao.web.mail.MailService;
import com.yunao.service.UserService;
import com.yunao.web.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@Slf4j
@RequestMapping("/mail")
public class MailSendController {
    @Autowired
    private MailService mailService;
    @Autowired
    private IsearchService service;
    @Autowired
    private UserService userService;

    @UserLoginToken
    @RequestMapping("/findUserEmail")
    public String findUserEmail(){
        User user = TokenUtil.getTokenUser(userService);
        return user.getEmail();
    }

    @RequestMapping("/sendMailByIds")
    public ResultVO sendMailByIds(String ids,String email){
        if (StringUtils.isEmpty(email)||!isMailAddress(email)){
            return ResultVOUtil.error(ResultEnum.EMAIL_ADDR_ERROR);
        }
        Map map = new HashMap<>();
        map.put("id",ids);
        Articles articles = service.query(map);
        // 邮件正文
        String mailText = mailService.getMailTemplate(articles.getData());
        mailService.send("云奥舆情", email, mailText.replace("$param",
                    Base64.getEncoder().encodeToString(email.getBytes())));
        log.info("Send mail: " + email);
        return ResultVOUtil.success();
    }


    private boolean isMailAddress(String addr) {
        String regex = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        return Pattern.compile(regex).matcher(addr).matches();
    }
}
